package com.tanhua.dubbo.server.api;

import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.pojo.Comment;
import com.tanhua.dubbo.server.pojo.Video;
import com.tanhua.dubbo.server.vo.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author why
 */
@Service
public class ManageCommentApiImpl implements ManageCommentApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public PageInfo<Comment> queryComments(Integer page, Integer pageSize, String sortProp, String sortOrder, String publishId) {
        PageInfo<Comment> pageInfo=new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);

        PageRequest pageRequest=null;
        if (StringUtils.equalsIgnoreCase(sortOrder,"descending")){
            pageRequest =PageRequest.of(page-1,pageSize, Sort.by(Sort.Order.desc(sortProp)));
        }else {
            pageRequest =PageRequest.of(page-1,pageSize,Sort.by(Sort.Order.asc(sortProp)));
        }

        Query query=Query.query(Criteria.where("publishId").is(new ObjectId(publishId)).and("commentType").is(2)).with(pageRequest);
        List<Comment> comments = this.mongoTemplate.find(query, Comment.class);

        if (CollectionUtils.isEmpty(comments)){
            return pageInfo;
        }

        /**
         * 总评论数
         */
        Query queryCount=Query.query(Criteria.where("publishId").is(new ObjectId(publishId)).and("commentType").is(2));
        long count = this.mongoTemplate.count(queryCount, Video.class);

        pageInfo.setTotal((int) count);
        pageInfo.setRecords(comments);

        return pageInfo;

    }
}
